package cn.guyouda.algorithms;

import java.util.Iterator;

/**
 * @param <Item> 基于链表的堆栈实现
 * @author Youda
 */
public class Stack<Item> implements Iterable<Item> {


    private int COUNT; //栈元素数量
    private Node first; //栈顶元素

    /**
     * 节点定义
     *
     * @author Youda
     */
    private class Node {
        Item item;
        Node next;
    }

    //判断栈是否为空
    public boolean isEmpty() {
        return COUNT == 0;
        // return first == null;
    }

    //获取栈元素数量
    public int getCount() {
        return COUNT;
    }

    //进栈
    public void pust(Item item) {

        //新元素插入栈顶
        Node node = first;
        first = new Node();
        first.item = item;
        first.next = node;

        COUNT++;
    }

    //出栈
    public Item pop() {

        //返回第一个元素并删除
        Item item = first.item;
        first = first.next;
        COUNT--;
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        // TODO Auto-generated method stub
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {

        private Node currentNode = first;

        @Override
        public boolean hasNext() {
            return currentNode != null;
        }

        @Override
        public Item next() {
            Item item = currentNode.item;
            currentNode = currentNode.next;
            return item;
        }

    }
}
